// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
	_before: function() { // 通用预处理器

	},
	async QBPay(list = [], user_id, address = {},total=0) {
		// 开启阿里事务
		const transaction = await db.startTransaction()
		try {
			let time = Date.now()
			// 扣除用户
			let userRes = await transaction.collection('uni-id-users').doc(user_id).get()
			if (userRes.data) {
				const updateUserMoney = await transaction.collection('uni-id-users').doc(user_id).update({
					money:dbCmd.inc(-total)
				})
				// 添加订单
				const addOrder = await transaction.collection('order').add({
					type:"商品订单",
					pay_type:"QB",
					total_fee:total,
					user_id:user_id,
					platform:"h5",
					status:2,
					wait_status:1,
					address:address,
					goods_list:list,
					create_time:time,//时间
					update_time:time,//时间
					paid_time:time,//时间
				})
				// 提交正常的数据库操作
				const updateUserRes = await transaction.collection('uni-id-users').doc(user_id).get()
				if(updateUserRes.data.money<0){//前扣超了
					await transaction.rollback(-100)
					return {
						success:false,
						error: `rollback`,
						rollbackCode: -100,
					}
				}else{
					await transaction.commit()
				}
				return{
					success:true
				}
			} else {
				await transaction.rollback()
				return {
					success: false,
					error: `rollback`,
					rollbackCode: -100,
				}
			}
		} catch (e) {
			// 等待事务回滚
			await transaction.rollback()
			return {
				success: false,
				error: e
			}
		}
	}
}

